package com.asktgapp.user.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toolbar;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.model.IndexVO;
import com.asktgapp.model.Person;
import com.asktgapp.model.QuestionDetailVO;
import com.asktgapp.model.UsedMachineDetailVO;
import com.asktgapp.model.UsedMachineVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.ShareActivity;
import com.asktgapp.widget.BannerViewpPager;
import com.asktgapp.widget.UseMachinDetailBanner;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/23
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:二手设备详情
 * 修改时间 2018年7月21日18:54:57
 */

public class UsedMachineDetailFragment extends BaseFragment {
    @InjectView(R.id.banner)
    UseMachinDetailBanner mBanner;

    @InjectView(R.id.tv_used_machine_name)
    TextView mTitle;
    @InjectView(R.id.tv_price)
    TextView mPrice;
    @InjectView(R.id.tv_time)
    TextView mTime;
    @InjectView(R.id.tv_model)
    TextView mModel;
    @InjectView(R.id.tv_address)
    TextView mAddress;
    @InjectView(R.id.tv_made_date)
    TextView mMadeDate;
    @InjectView(R.id.tv_work_hour)
    TextView mWorkHour;
    @InjectView(R.id.tv_state)
    TextView mState;
    @InjectView(R.id.tv_link_name)
    TextView mLinkName;
    @InjectView(R.id.tv_link_phone)
    TextView mLinkPhone;
    @InjectView(R.id.tv_info)
    TextView mInfo;
    @InjectView(R.id.tv_tonnage)
    TextView mTonnage;
    @InjectView(R.id.tv_brand)
    TextView mBrand;
    @InjectView(R.id.tv_sendSMS)
    TextView mSendSMS;
    @InjectView(R.id.tv_callPhone)
    TextView mCallPhone;
    @InjectView(R.id.tv_guanzhu)
    TextView mGuanzhu;
    @InjectView(R.id.myToolbar)
    LinearLayout myToolbar;
    @InjectView(R.id.myBack)
    TextView myBack;
    @InjectView(R.id.myToolbarTitle)
    TextView myToolbarTitle;
    @InjectView(R.id.myToolbarShare)
    TextView myToolbarShare;
    @InjectView(R.id.scrollView)
    NestedScrollView scrollView;
    @InjectView(R.id.tvNumber)
    TextView tvNumber;
    @InjectView(R.id.llGuanZ)
    LinearLayout llGuanZ;
    private String machineId;

    private UsedMachineDetailVO usedMachine;
    private boolean isFollow = false;
    @InjectView(R.id.ivGZ)
    ImageView ivGZ;

    private void setUI(UsedMachineDetailVO bean) {
        mTitle.setText(bean.getTitle());
        myToolbarTitle.setText(bean.getTitle());
        DecimalFormat df = new DecimalFormat("0.00");
        mPrice.setText(df.format(bean.getPrice()));
        Date date = Util.StrToDate(bean.getAdd_time(), "yyyy.MM.dd HH:mm:ss");
        String timeStr = Utils.getAskTime(date);
        mTime.setText(timeStr);
        mModel.setText(bean.getModel());
        mAddress.setText(bean.getPro_name().replace("省", "") + " " + bean.getCity_name().replace("市", ""));
        mMadeDate.setText(Utils.getDateYear(bean.getProduction_date()));
        mWorkHour.setText(String.valueOf(Utils.D2I(bean.getWorking_hours())) + "小时");
        mTonnage.setText(String.valueOf(Utils.DtS(bean.getTonnage())));
        mLinkName.setText(bean.getLink_name());
        mLinkPhone.setText(bean.getLink_phone());
        mInfo.setText(bean.getInfo());
        mBrand.setText(bean.getBrand());
        tvNumber.setText(bean.getViewNum());
        //待售
        if (bean.getState() == 0) {
            mState.setText("待售");
        } else {
            mState.setText("已售");
        }
        String[] url = bean.getBanner_pic().split(",");
        List<String> list = new ArrayList();
        for (int i = 0; i < url.length; i++) {
            list.add(url[i]);
        }
        mBanner.loadBannerData(list);
        //0没有关注 1关注
        if (bean.getIs_follow() == 0) {
            isFollow = false;
            mGuanzhu.setText("未关注");
            ivGZ.setImageResource(R.mipmap.weiguanzhu);
        } else {
            isFollow = true;
            mGuanzhu.setText("已关注");
            ivGZ.setImageResource(R.mipmap.yiguanzh);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_used_machine_detail, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
//        getBaseActivity().setBackNavigationIcon();
//        getBaseActivity().setStatusBar();
//        getBaseActivity().hideNavBar();
        getBaseActivity().getToolbar().setVisibility(View.GONE);
        myBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBaseActivity().onBackPressed();
            }
        });
        myToolbarShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ShareActivity.class);
                intent.putExtra("type", 0);
                intent.putExtra("id", usedMachine.getId());
                startActivity(intent);
            }
        });
        myToolbarTitle.setAlpha(0);
//        setHasOptionsMenu(true);
        machineId = getActivity().getIntent().getStringExtra("id");
//        priceUnit = getActivity().getIntent().getStringExtra("unit");
        mCallPhone.setOnClickListener(this);
        mSendSMS.setOnClickListener(this);
        llGuanZ.setOnClickListener(this);

        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY >= mBanner.getHeight()) {
                    myToolbar.setBackgroundColor(Color.argb(255, 51, 153, 254));
//                    bindingView.homeSearch.setAlpha(1);
                    myToolbarTitle.setAlpha(1);
                } else {
                    myToolbar.setBackgroundColor(Color.argb(0, 51, 153, 254));
//                    bindingView.homeSearch.setAlpha(scrollY / 200f);
                    myToolbarTitle.setAlpha(0);
                }
            }
        });
    }

    private void doFollow(int i) {
        if (checkIsLogin("登录后可体验更多内容")) {
            Apiservice apiservice = ApiUtil.getInstance().create();
            HashMap params = new HashMap();
            params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
            //0:二手机 1:设备出租 2:设备求租 3:工程师
            params.put("type", 0);
            params.put("temp", i);
            params.put("id", machineId);
            showProgress(getClass().getSimpleName());
            Call<ApiResponseBody> call = apiservice.follow(params);
            call.enqueue(new Callback<ApiResponseBody>() {
                @Override
                public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                    dismissProgress();
                    if (response.isSuccessful()) {
                        if (isFollow) {
                            mGuanzhu.setText("未关注");
                            ivGZ.setImageResource(R.mipmap.weiguanzhu);
//                            mGuanzhu.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.weiguanzhu, 0, 0);
                        } else {
                            mGuanzhu.setText("已关注");
                            ivGZ.setImageResource(R.mipmap.yiguanzh);
//                            mGuanzhu.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.yiguanzh, 0, 0);
                        }
                        isFollow = !isFollow;
                    } else {
                        showTost(response.raw().message(), 1);
                    }
                }

                @Override
                public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                    dismissProgress();
                    ApiException apiException = ExceptionHandle.handleException(t);
                    if (apiException.isTokenInvalid()) {
                        showUnLoginSnackbar();
                    } else if (apiException.isNetConnected()) {
                        showSetNetworkSnackbar();
                    } else {
                        showTost(apiException.getMessage(), 0);
                    }
                }
            });
        }
    }

    @Override
    public void loadData() {
        visibleLoading();
        final Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("id", machineId);
        Call<ApiResponseBody<UsedMachineDetailVO>> call = apiservice.getTwoHard(params);
        call.enqueue(new Callback<ApiResponseBody<UsedMachineDetailVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<UsedMachineDetailVO>> call, Response<ApiResponseBody<UsedMachineDetailVO>> response) {
                inVisibleLoading();
                if (response.isSuccessful()) {
                    usedMachine = response.body().getResult();
                    if(usedMachine!=null)
                        setUI(usedMachine);
                    else
                        showTost("加载失败", 1);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<UsedMachineDetailVO>> call, Throwable t) {
                inVisibleLoading();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        mBanner.onBannerPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        mBanner.onBannerResume();
    }

//    @Override
//    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        inflater.inflate(R.menu.share, menu);
//        super.onCreateOptionsMenu(menu, inflater);
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        Intent intent = new Intent(getActivity(), ShareActivity.class);
//        intent.putExtra("type", 0);
//        intent.putExtra("id", usedMachine.getId());
//        startActivity(intent);
//        return super.onOptionsItemSelected(item);
//    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_sendSMS:
                if (checkIsLogin("登录后可查看更多内容"))
                    Utils.sendMessage(getActivity(), usedMachine.getLink_phone());
                break;
            case R.id.tv_callPhone:
                if (checkIsLogin("登录后可查看更多内容"))
                    Utils.callPhone(getActivity(), usedMachine.getLink_phone());
                break;
            case R.id.llGuanZ:
                //0取消关注 1关注
                if (isFollow) {
                    doFollow(0);
                } else {
                    doFollow(1);
                }

                break;
        }
    }
}
